import 'package:dio/dio.dart';
import 'package:playtruly/common/services/http.dart';
import 'package:playtruly/common/models/index.dart';
import 'package:playtruly/common/utils/encryption_util.dart';
import 'dart:developer' as developer;

/// 用户相关API
class UserApi {
  /// 发送短信验证码（严格按照MyApplication2实现）
  /// [userPhone] 手机号
  /// [verificationCode] 自生成的验证码（6位数字）
  /// 返回SmsResponse对象
  static Future<SmsResponse> sendSmsCode({
    required String userPhone,
    required String verificationCode,
  }) async {
    try {
      developer.log('🔄 =============== 开始发送短信验证码 ===============');
      developer.log('📱 手机号: $userPhone');
      developer.log('🔢 验证码: $verificationCode');
      
      // 生成时间戳
      final timestamp = (DateTime.now().millisecondsSinceEpoch ~/ 1000).toString();
      
      // 构建请求数据（严格按照MyApplication2格式）
      final requestData = {
        'userPhone': userPhone, // 字符串格式
        'userCode': verificationCode, // 验证码字段（与MyApplication2一致）
        'timestamp': timestamp, // 字符串格式的时间戳
      };
      
      developer.log('📊 请求参数（加密前）: $requestData');
      
      // 🔥 严格按照MyApplication2实现：必须使用AES加密
      developer.log('🔐 开始AES加密短信验证码数据...');
      final encryptedPayload = EncryptionUtil.createEncryptedPayload(requestData);
      
      developer.log('🚀 准备发送加密短信请求到: /users/send_sms_code/');
      developer.log('📦 加密载荷: $encryptedPayload');

      // 发送加密请求
      final response = await HttpService.to.post(
        '/users/send_sms_code/',
        data: encryptedPayload,
      );

      developer.log('✅ 短信验证码响应: $response');

      // 解析响应为SmsResponse对象
      final smsResponse = SmsResponse.fromJson(response);
      
      if (smsResponse.isSuccess) {
        developer.log('🎉 短信验证码发送成功！');
        developer.log('📝 消息: ${smsResponse.message}');
      } else {
        developer.log('❌ 短信验证码发送失败: ${smsResponse.message}');
      }
      
      return smsResponse;
    } catch (e) {
      developer.log('💥 短信验证码API异常: $e');
      // 如果出现异常，返回失败响应
      return SmsResponse(
        status: 'error',
        message: '发送验证码失败: ${e.toString()}',
      );
    }
  }

  /// 发送短信验证码（原始方法，保留兼容性）
  static Future<Map<String, dynamic>> sendSmsCodeLegacy({
    required String userPhone,
    String codeType = 'login',
  }) async {
    return await HttpService.to.post(
      '/users/send_sms_code/',
      data: {
        'userPhone': userPhone,
        'codeType': codeType,
      },
    );
  }
  
  /// 检查手机号是否存在并获取用户信息（严格按照MyApplication2实现）
  static Future<UserCheckResponse> checkPhone({
    required String userPhone,
  }) async {
    try {
      developer.log('🔄 =============== 开始检查用户信息 ===============');
      developer.log('📱 手机号: $userPhone');
      
      // 生成时间戳
      final timestamp = (DateTime.now().millisecondsSinceEpoch ~/ 1000).toString();
      
      // 构建请求数据（严格按照MyApplication2格式）
      final requestData = {
        'userPhone': userPhone, // 字符串格式
        'timestamp': timestamp, // 字符串格式的时间戳
      };
      
      developer.log('📊 请求参数（加密前）: $requestData');
      
      // 🔥 严格按照MyApplication2实现：必须使用AES加密
      developer.log('🔐 开始AES加密用户信息查询数据...');
      final encryptedPayload = EncryptionUtil.createEncryptedPayload(requestData);
      
      developer.log('🚀 准备发送加密查询请求到: /users/check_phone/');
      developer.log('📦 加密载荷: $encryptedPayload');
      
      final response = await HttpService.to.post(
        '/users/check_phone/',
        data: encryptedPayload,
      );

      developer.log('✅ 用户信息查询响应: $response');

      // 解析响应为UserCheckResponse对象
      final checkResponse = UserCheckResponse.fromJson(response);
      
      if (checkResponse.isSuccess) {
        developer.log('🎉 用户信息查询成功！');
        developer.log('👤 用户存在: ${checkResponse.exists}');
        if (checkResponse.data != null) {
          developer.log('📝 用户名: ${checkResponse.data!.username}');
          developer.log('🆔 用户ID: ${checkResponse.data!.userid}');
          developer.log('❤️ 点赞数: ${checkResponse.data!.userLikes}');
          developer.log('👥 粉丝数: ${checkResponse.data!.userFollowers}');
          developer.log('💰 积分: ${checkResponse.data!.userPoints}');
          developer.log('🎂 年龄: ${checkResponse.data!.userAge}');
          developer.log('⚥ 性别: ${checkResponse.data!.userGender}');
          developer.log('✍️ 签名: ${checkResponse.data!.userSignature}');
        }
      } else {
        developer.log('❌ 用户信息查询失败: ${checkResponse.message}');
      }
      
      return checkResponse;
    } catch (e) {
      developer.log('💥 用户信息查询API异常: $e');
      // 如果出现异常，返回失败响应
      return UserCheckResponse(
        status: 'error',
        exists: false,
        message: '查询用户信息失败: ${e.toString()}',
        accountType: '',
      );
    }
  }

  /// 检查手机号是否存在（原始方法，保留兼容性）
  static Future<Map<String, dynamic>> checkPhoneLegacy({
    required String userPhone,
  }) async {
    return await HttpService.to.post(
      '/users/check_phone/',
      data: {
        'userPhone': userPhone,
      },
    );
  }
  /// 登录
  static Future<Map<String, dynamic>> login({
    required String username,
    required String password,
  }) async {
    return await HttpService.to.post(
      '/users/check_phone',
      data: {
        'userPhone': username,
        'userPassword': password,
      },
    );
  }
  
  /// 注册
  static Future<Map<String, dynamic>> register({
    required String username,
    required String password,
    required String email,
    String? code,
  }) async {
    return await HttpService.to.post(
      '/user/register',
      data: {
        'username': username,
        'password': password,
        'email': email,
        if (code != null) 'code': code,
      },
    );
  }
  
  /// 获取用户信息
  static Future<Map<String, dynamic>> getUserInfo() async {
    return await HttpService.to.get('/user/info');
  }
  
  /// 更新用户信息 (新版API - 使用AES加密，与MyApplication2保持完全一致)
  static Future<UserUpdateResponse> updateUserInfo({
    required String userPhone,
    String? username,
    String? userSignature,
    String? userGender,
    String? userBirthday, // 📝 保持与MyApplication2一致，使用生日而非年龄
    String? userFrequentPlaces,
    List<String>? userHobbies, // 📝 固定为5个爱好：["吃", "喝", "玩", "乐", "购"]
    String? userAvatarUrl,
    List<String>? userImgUrls, // 📝 新增：用户相册图片URLs
  }) async {
    try {
      developer.log('🔄 =============== 开始更新用户信息（AES加密） ===============');
      developer.log('📱 手机号: $userPhone');
      
      // 构建请求数据，与MyApplication2参数完全一致
      final requestData = <String, dynamic>{
        'userPhone': userPhone,
      };
      
      // 添加可选参数，按照MyApplication2的参数结构
      if (username != null) requestData['username'] = username;
      if (userAvatarUrl != null) requestData['userAvatarUrl'] = userAvatarUrl;
      if (userSignature != null) requestData['userSignature'] = userSignature;
      if (userGender != null) requestData['userGender'] = userGender;
      if (userBirthday != null) requestData['userBirthday'] = userBirthday;
      if (userFrequentPlaces != null) requestData['userFrequentPlaces'] = userFrequentPlaces;
      
      // 🔥 修复：爱好参数支持用户自定义选择（与MyApplication2一致）
      if (userHobbies != null) {
        requestData['userHobbies'] = userHobbies;
        developer.log('🍽️ 设置用户选择的爱好: $userHobbies');
      }
      
      // 📝 相册图片URLs：与MyApplication2保持一致
      if (userImgUrls != null) {
        requestData['userImgUrls'] = userImgUrls;
        developer.log('🖼️ 设置相册图片: ${userImgUrls.length}张');
      }
      
      // 📝 添加时间戳，与MyApplication2保持一致
      requestData['timestamp'] = DateTime.now().millisecondsSinceEpoch;
      
      developer.log('📊 请求参数（加密前）: $requestData');
      
      // 🔥 使用AES加密
      developer.log('🔐 开始AES加密用户信息更新数据...');
      final encryptedPayload = EncryptionUtil.createEncryptedPayload(requestData);
      
      developer.log('🚀 准备发送加密请求到: /users/update/');

      final response = await HttpService.to.post(
        '/users/update/',
        data: encryptedPayload,
      );

      developer.log('✅ 用户信息更新响应: $response');
      return UserUpdateResponse.fromJson(response);
    } catch (e) {
      developer.log('💥 更新用户信息异常: $e');
      return UserUpdateResponse(
        status: 'error',
        message: '更新用户信息失败: ${e.toString()}',
        affectedRows: 0,
      );
    }
  }

  /// 更新用户信息 (旧版API，保持兼容性)
  static Future<Map<String, dynamic>> updateUserInfoLegacy({
    String? nickname,
    String? avatar,
    String? gender,
  }) async {
    return await HttpService.to.put(
      '/user/info',
      data: {
        if (nickname != null) 'nickname': nickname,
        if (avatar != null) 'avatar': avatar,
        if (gender != null) 'gender': gender,
      },
    );
  }
  
  /// 上传用户图片 (新版API - 根据接口文档1.1)
  static Future<UserImageUploadResponse> uploadUserImage({
    required int userId,
    required String filePath,
    Function(int sent, int total)? onProgress,
  }) async {
    try {
      // 创建FormData，根据服务器实际要求的格式
      FormData formData = FormData.fromMap({
        'user_id': userId, // 服务器要求的字段名
        'file': await MultipartFile.fromFile(
          filePath,
          filename: 'avatar.jpg', // 给文件一个名称
        ),
      });
      
      final response = await HttpService.to.upload(
        '/users/upload_image/',
        data: formData,
        onSendProgress: onProgress,
      );

      return UserImageUploadResponse.fromJson(response);
    } catch (e) {
      return UserImageUploadResponse(
        status: 'error',
        message: '图片上传失败: ${e.toString()}',
      );
    }
  }

  /// 上传头像 (旧版API，保持兼容性)
  static Future<Map<String, dynamic>> uploadAvatarLegacy({
    required String filePath,
  }) async {
    // 创建FormData
    FormData formData = FormData.fromMap({
      'file': await MultipartFile.fromFile(filePath),
    });
    
    return await HttpService.to.upload(
      '/user/avatar',
      data: formData,
      onSendProgress: (int sent, int total) {
        // 上传进度
        final progress = sent / total;
        print('上传进度: ${(progress * 100).toStringAsFixed(2)}%');
      },
    );
  }
  
  /// 退出登录
  static Future<void> logout() async {
    await HttpService.to.post('/user/logout');
  }

  /// 实名认证 (新版API - 使用AES加密)
  static Future<RealnameAuthResponse> realnameAuth({
    required int userId,
    required String realName,
    required String idCardNo,
  }) async {
    try {
      developer.log('🔄 =============== 开始实名认证（AES加密） ===============');
      developer.log('👤 用户ID: $userId');
      developer.log('📝 姓名: $realName');
      
      // 创建请求数据（🔥 修复：与MyApplication2保持一致，使用id_card_no）
      final requestData = {
        'userid': userId,
        'name': realName,
        'id_card_no': idCardNo,  // 🔥 修复：改为服务端期望的字段名
      };

      developer.log('📊 请求参数（加密前）: $requestData');
      
      // 🔥 使用AES加密
      developer.log('🔐 开始AES加密实名认证数据...');
      final encryptedPayload = EncryptionUtil.createEncryptedPayload(requestData);
      
      developer.log('🚀 准备发送加密请求到: /users/real-name-auth/');

      final response = await HttpService.to.post(
        '/users/real-name-auth/',
        data: encryptedPayload,
      );

      developer.log('✅ 实名认证响应: $response');
      return RealnameAuthResponse.fromJson(response);
    } catch (e) {
      developer.log('💥 实名认证API异常: $e');
      return RealnameAuthResponse(
        status: 'error',
        message: '实名认证失败: ${e.toString()}',
      );
    }
  }

  /// 用户注册 (新版API - 根据接口文档1.4 和 MyApplication2实现)
  /// 通过手机号创建新用户账户
  static Future<UserRegisterResponse> registerWithPhone({
    required String userPhone,
    required String userType, // "0"=个人用户, "1"=商家用户
    String? username,
    String? userEmail,
    String? userAvatarUrl,
    int? userAge,
    String? userGender,
    String? userSignature,
    List<String>? userTags,
    String? userCity,
    bool generateToken = true, // 是否生成融云token
  }) async {
    try {
      developer.log('🔄 =============== 开始用户注册 ===============');
      developer.log('📱 手机号: $userPhone');
      developer.log('👤 用户类型: $userType (0=个人, 1=商家)');
      developer.log('🎯 生成Token: $generateToken');

      // 生成时间戳
      final timestamp = (DateTime.now().millisecondsSinceEpoch ~/ 1000).toString();
      
      // 创建注册请求数据（严格按照MyApplication2格式）
      final request = UserRegisterRequest(
        userPhone: userPhone, // 字符串
        userCode: userType, // 字符串："0"=个人, "1"=商家
        genToken: generateToken ? "1" : "0", // 字符串，与MyApplication2一致
        username: username,
        userEmail: userEmail,
        userAvatarUrl: userAvatarUrl,
        userAge: userAge,
        userGender: userGender,
        userSignature: userSignature,
        userTags: userTags,
        userCity: userCity,
        timestamp: timestamp, // 字符串格式的时间戳
      );

      final requestData = request.toApiJson();
      developer.log('📊 注册请求参数（加密前）: $requestData');
      
      // 🔥 严格按照MyApplication2实现：必须使用AES加密
      developer.log('🔐 开始AES加密注册数据...');
      final encryptedPayload = EncryptionUtil.createEncryptedPayload(requestData);
      
      developer.log('🚀 准备发送加密注册请求到: /users/create_with_phone/');
      developer.log('📦 加密载荷: $encryptedPayload');
      developer.log('📝 加密载荷类型: ${encryptedPayload.runtimeType}');

      // 发送加密注册请求（端口2233，与MyApplication2一致）
      final response = await HttpService.to.post(
        '/users/create_with_phone/',
        data: encryptedPayload,
      );

      developer.log('✅ 注册响应: $response');

      final registerResponse = UserRegisterResponse.fromJson(response);
      
      if (registerResponse.isSuccess) {
        developer.log('🎉 用户注册成功！');
        developer.log('👤 用户ID: ${registerResponse.userId}');
        developer.log('📝 消息: ${registerResponse.message}');
      } else {
        developer.log('❌ 用户注册失败: ${registerResponse.message}');
      }

      return registerResponse;
    } catch (e) {
      developer.log('💥 用户注册API异常: $e');
      return UserRegisterResponse(
        status: 'error',
        message: '用户注册失败: ${e.toString()}',
      );
    }
  }

  /// 获取用户发布的内容（使用AES加密）
  /// [userId] 用户ID（必填）
  /// [days] 查询天数，默认365天，即查询最近一年的数据（可选）
  /// 返回用户发布的活动、评论等内容
  static Future<UserContentResponse> getUserContent({
    required int userId,
    int? days,
  }) async {
    try {
      developer.log('🔄 =============== 开始获取用户发布内容（AES加密） ===============');
      developer.log('👤 用户ID: $userId');
      developer.log('📅 查询天数: ${days == null ? "所有历史数据" : "${days}天"}');

      // 生成时间戳
      final timestamp = (DateTime.now().millisecondsSinceEpoch ~/ 1000).toString();

      // 构建请求参数
      final request = UserContentRequest(
        userId: userId,
        days: days,
        timestamp: int.parse(timestamp),
      );

      final requestData = request.toJson();
      developer.log('📊 请求参数（加密前）: $requestData');
      
      // 🔥 使用AES加密
      developer.log('🔐 开始AES加密用户内容查询数据...');
      final encryptedPayload = EncryptionUtil.createEncryptedPayload(requestData);
      
      developer.log('🚀 准备发送加密请求到: /users/content/');

      // 发送请求
      final response = await HttpService.to.post(
        '/users/content/',
        data: encryptedPayload,
      );

      developer.log('📨 用户内容查询响应: $response');

      // 解析响应
      final contentResponse = UserContentResponse.fromJson(response);

      if (contentResponse.isSuccess) {
        developer.log('✅ 用户内容查询成功');
        developer.log('📝 活动数量: ${contentResponse.activities.length}');
        developer.log('📝 已结束活动数量: ${contentResponse.endedActivities.length}');
        developer.log('📝 评论数量: ${contentResponse.comments.length}');
        developer.log('📝 参与活动数量: ${contentResponse.participatedActivities.length}');
        developer.log('📊 统计信息: ${contentResponse.contentStats}');
      } else {
        developer.log('❌ 用户内容查询失败: ${contentResponse.message ?? "未知错误"}');
      }

      return contentResponse;
    } catch (e) {
      developer.log('💥 用户内容查询异常: $e');
      return UserContentResponse(
        status: 'error',
        message: '查询用户内容失败: ${e.toString()}',
        activities: [],
        endedActivities: [],
        comments: [],
        participatedActivities: [],
      );
    }
  }

  /// 获取用户过滤内容（查看其他用户信息）
  /// [userId] 目标用户ID（必填）
  /// [contentType] 内容类型："activities"或"comments"（必填）
  /// 返回用户基本信息和对应的活动或评论列表
  static Future<UserFilteredContentResponse> getUserFilteredContent({
    required int userId,
    required String contentType,
  }) async {
    try {
      developer.log('🔄 =============== 开始获取用户过滤内容（AES加密） ===============');
      developer.log('👤 目标用户ID: $userId');
      developer.log('📝 内容类型: $contentType');

      // 创建请求模型
      final request = UserFilteredContentRequest(
        userId: userId,
        contentType: contentType,
      );

      final requestData = request.toJson();
      developer.log('📊 请求参数（加密前）: $requestData');
      
      // 🔥 使用AES加密
      developer.log('🔐 开始AES加密用户过滤内容查询数据...');
      final encryptedPayload = EncryptionUtil.createEncryptedPayload(requestData);
      
      developer.log('🚀 准备发送加密请求到: /users/filtered_content/');

      // 发送请求
      final response = await HttpService.to.post(
        '/users/filtered_content/',
        data: encryptedPayload,
      );

      developer.log('📨 用户过滤内容查询响应: $response');

      // 解析响应
      final filteredContentResponse = UserFilteredContentResponse.fromJson(response);

      if (filteredContentResponse.isSuccess) {
        developer.log('✅ 用户过滤内容查询成功');
        if (filteredContentResponse.user != null) {
          final user = filteredContentResponse.user!;
          developer.log('👤 用户信息:');
          developer.log('  📛 用户名: ${user.username}');
          developer.log('  🆔 用户ID: ${user.userid}');
          developer.log('  🔗 头像: ${user.userAvatarUrl}');
          developer.log('  ⭐ 等级: ${user.userLevel}');
          developer.log('  👥 粉丝数: ${user.userFollowers}');
          developer.log('  👍 点赞数: ${user.userLikes}');
          developer.log('  ✍️ 签名: ${user.userSignature}');
          developer.log('  🏷️ 标签: ${user.userTags}');
          developer.log('  🎯 爱好: ${user.userHobbies}');
          developer.log('  📍 常出没地: ${user.userFrequentPlaces}');
          developer.log('  🏙️ 城市: ${user.userCity}');
        }
        developer.log('🤝 好友数量: ${filteredContentResponse.friendCount}');
        if (contentType == 'activities' && filteredContentResponse.activities != null) {
          developer.log('📝 活动数量: ${filteredContentResponse.activities!.length}');
        }
        if (contentType == 'comments' && filteredContentResponse.comments != null) {
          developer.log('💬 评论数量: ${filteredContentResponse.comments!.length}');
        }
      } else {
        developer.log('❌ 用户过滤内容查询失败: ${filteredContentResponse.message ?? "未知错误"}');
      }

      return filteredContentResponse;
    } catch (e) {
      developer.log('💥 用户过滤内容查询异常: $e');
      return UserFilteredContentResponse(
        status: 'error',
        message: '查询用户过滤内容失败: ${e.toString()}',
      );
    }
  }

  /// 查询用户历史记录（使用AES加密）
  /// 对应MyApplication2的历史记录功能
  /// [userId] 用户ID（必填）
  /// [date] 查询日期，格式：YYYY-MM-DD（必填）
  /// [type] 查询类型，默认"all"（可选）
  /// 返回用户的历史活动和评论记录
  static Future<UserHistoryResponse> getUserHistory({
    required int userId,
    required String date,
    String type = 'all',
  }) async {
    try {
      developer.log('🔄 =============== 开始查询用户历史记录（AES加密） ===============');
      developer.log('👤 用户ID: $userId');
      developer.log('📅 查询日期: $date');
      developer.log('📝 查询类型: $type');

      // 生成时间戳
      final timestamp = (DateTime.now().millisecondsSinceEpoch ~/ 1000).toString();

      // 创建请求模型（严格按照MyApplication2格式）
      final request = UserHistoryRequest(
        userId: userId,
        date: date,
        type: type,
        timestamp: timestamp,
      );

      final requestData = request.toJson();
      developer.log('📊 请求参数（加密前）: $requestData');
      
      // 🔥 严格按照MyApplication2实现：必须使用AES加密
      developer.log('🔐 开始AES加密历史记录查询数据...');
      final encryptedPayload = EncryptionUtil.createEncryptedPayload(requestData);
      
      developer.log('🚀 准备发送加密请求到: /users/daily_activities_comments/');

      // 发送请求
      final response = await HttpService.to.post(
        '/users/daily_activities_comments/',
        data: encryptedPayload,
      );

      developer.log('📨 用户历史记录查询响应: $response');

      // 解析响应
      final historyResponse = UserHistoryResponse.fromJson(response);

      if (historyResponse.isSuccess) {
        developer.log('✅ 用户历史记录查询成功');
        developer.log('📝 历史记录数量: ${historyResponse.data.length}');
        developer.log('📊 总数: ${historyResponse.total}');
        developer.log('📅 查询日期: ${historyResponse.date}');
        
        // 打印前几条记录的详情
        for (int i = 0; i < historyResponse.data.length && i < 3; i++) {
          final item = historyResponse.data[i];
          developer.log('  📋 记录${i + 1}: ${item.type} - ${item.title} (${item.publishTime})');
        }
      } else {
        developer.log('❌ 用户历史记录查询失败: ${historyResponse.message ?? "未知错误"}');
      }

      return historyResponse;
    } catch (e) {
      developer.log('💥 用户历史记录查询异常: $e');
      return UserHistoryResponse(
        status: 'error',
        message: '查询用户历史记录失败: ${e.toString()}',
        data: [],
        total: 0,
        date: date,
        userId: userId.toString(),
      );
    }
  }
} 